<?php
namespace app\common\lib;

use think\Db;
class SendIntegralNew{
    /**
     * @param $id 任务.公告.积分奖扣.请假 表id
     * @param $type 类型 1公告  2任务 3积分奖扣 4请假
     * @param int $first_integtal 积分奖扣初审人送分值
     * @param int $record_integral 积分奖扣记录人送分值
     */
    //发放积分
    static public function send($id,$type,$first_integral=0,$record_integral=0){
        if($type == 1){ //公告
            $info = M('com_notice')->where('id',$id)->find();
            //记录人加分
            $info['user_id'] = $info['record_user_id'];
            $record_b = M('com_config')->where('com_id',$info['com_id'])->value('record');
            self::add_record_integral($info,$record_b,0,21,true);
        }elseif($type == 2){//任务
            $info = M('com_task')->where('id',$id)->find();
            //记录人加分
            $info['user_id'] = $info['record_user_id'];
            $record_b = M('com_config')->where('com_id',$info['com_id'])->value('record');
            self::add_record_integral($info,$record_b,0,17,true);
        }elseif($type == 3){//积分奖扣
            $info = M('com_integral_prize_buckle')->where('id',$id)->find();
            $info['name'] = $info['theme'];
            //参与人加分
            $take = M('com_integral_event_relation_users a')
                ->join('com_integral_prize_buckle_relation_event b','a.event_id=b.id','left')
                ->where('b.prize_buckle_id', $id)
                ->field('a.user_id,
                if(a.piece_rate>0,a.integral_b*a.piece_rate,a.integral_b) as integral_b,
                a.integral_a,b.event_id')
                ->select();
            foreach ($take as $k=>$v){
                $info['user_id'] = $v['user_id'];
                self::add_record_integral($info, $v['integral_b'], $v['integral_a'], $v['event_id'], false);
            }
            //记录人达到条件奖分
            $sys = M('com_config')->where('com_id',$info['com_id'])->field('record_people_num,record_event_num')->find();
            //事件数
            $event_count = M('com_integral_prize_buckle_relation_event')->where('prize_buckle_id',$id)->count();
            //人次数
            $people_count = count($take);
            if(!empty($sys['record_people_num'])){//主题人次
                $record_people_num = unserialize($sys['record_people_num']);
                //冒泡排序
                $prize_integral = 0;
                $record_people_num = self::data_sort($record_people_num,'people_sum');
                foreach ($record_people_num as $key=>$value){
                    if($people_count >=$value['people_sum']){
                        $prize_integral = $value['prize_integral'];
                        break;
                    }
                }
                if($prize_integral >0){
                    $info['user_id'] = $info['record_user_id'];
                    self::add_record_integral($info,$prize_integral,0,23,true);
                }
            }
            if(!empty($sys['record_event_num'])){//主题事件
                $record_event_num = unserialize($sys['record_event_num']);
                //冒泡排序
                $event_prize_integral = 0;
                $record_event_num = self::data_sort($record_event_num,'event_prize_integral');
                foreach ($record_event_num as $key=>$value){
                    if($event_count >=$value['prize_sum']){
                        $event_prize_integral = $value['event_prize_integral'];
                        break;
                    }
                }
                if($event_prize_integral >0){
                    $info['user_id'] = $info['record_user_id'];
                    self::add_record_integral($info,$event_prize_integral,0,24,true);
                }
            }
            //记录人和初审人加分
            //初审人加分
            if($first_integral>0){
                $info['user_id'] = $info['first_check_user_id'];
                self::add_record_integral($info,$first_integral,0,26,true);
            }
            if($record_integral>0){
                $info['user_id'] = $info['record_user_id'];
                self::add_record_integral($info,$record_integral,0,25,true);
            }
        }elseif($type == 4){//请假
            $info = M('com_leave')->where('id',$id)->find();
            $info['name'] = '请假';
            //请假扣分
            if($info['deduct_marks'] != 0){
                if($info['type'] == 1){
                    $number = 29;
                }elseif ($info['type'] == 2){
                    $number = 28;
                }elseif ($info['type'] == 3){
                    $number = 30;
                }
                self::add_record_integral($info,-abs($info['deduct_marks']),0,$number,true,0,3);
            }
            //固定扣分
            if($info['fixed_deduct'] != 0){
                self::add_record_integral($info,-abs($info['fixed_deduct']),0,31,true,0,1);
            }
        }
    }
    /**
     * @param $Info  包含['com_id','user_id'] 奖扣事件包含['id','com_id','user_id'] id:积分奖扣主题 user_id:事件参与人 com_id:企业id
     * @param $record_b B 分
     * @param $record_a  A分
     * @param $eventId 事件id
     * @param $status 是否系统事件
     * @param int $time
     * @param int $type  类型 0日常奖扣 1固定积分 fixed_id 2奖扣任务 type 3其他得分 type
     */
    //发放奖分
    public static function add_record_integral($Info, $record_b, $record_a, $eventId, $status,$time=0,$type=0)
    {
//        com_integral_prize_buckle
        if(empty($time)){
            $time = time();
        }
        //系统奖励
        if($status){//系统事件
            if(!in_array($eventId, [23,24,25,26])){  //非积分奖扣主题
                $arr = SystemEvent::names();
                $c_i_p_b = [
                    'com_id'=>$Info['com_id'],
                    'first_check_user_id'=>2,
                    'last_check_user_id'=>2,
                    'record_user_id'=>2,
                    'prize_buckle_time'=>$time,
                    'status'=>2,
                    'integral_b_add'=>$record_b,
                    'integral_a_add'=>$record_a,
                    'first_check_time'=>$time,
                    'last_check_time'=>$time,
                    'theme'=>date('Y-m-d', $time).'-'.$Info['name'].'-'.$arr[$eventId] ,
                    'create_time'=>$time,
                ];
                $c_i_p_b_ID = M('com_integral_prize_buckle')->insertGetId($c_i_p_b);
            }else{
                $c_i_p_b_ID = $Info['id'];
            }


            //com_integral_prize_buckle_relation_event
            $c_i_p_b_r_e = [
                'com_id'=>$Info['com_id'],
                'prize_buckle_id'=>$c_i_p_b_ID,
                'event_id' =>$eventId,
                'create_time'=>$time
            ];
            $c_i_p_b_r_e_ID = M('com_integral_prize_buckle_relation_event')->insertGetId($c_i_p_b_r_e);

            //com_integral_event_relation_users
            $c_i_e_r_u = [
                'com_id'=>$Info['com_id'],
                'event_id'=>$c_i_p_b_r_e_ID,
                'user_id'=>$Info['user_id'],
                'integral_b'=>$record_b,
                'integral_a'=>$record_a
            ];
            M('com_integral_event_relation_users')->insert($c_i_e_r_u);

        }else{
            //com_integral_prize_buckle_relation_event
            //非系统事件要获取主题id
            //积分奖扣参与人奖励分值
            $c_i_p_b_r_e_where = [
                'com_id'=>$Info['com_id'],
                'prize_buckle_id'=>$Info['id'],
                'event_id' =>$eventId,
            ];
            $c_i_p_b_r_e_ID = M('com_integral_prize_buckle_relation_event')->where($c_i_p_b_r_e_where)->value('id');
        }
        //修改用户积分
//        users
        $user_id = $Info['user_id'];
        $usersUpdate = [];
        if(!empty($record_a)){
            $usersUpdate['integral_a'] = Db::raw('integral_a+'.$record_a);
        }
        if(!empty($record_b)){
            $usersUpdate['integral_b'] = Db::raw('integral_b+'.$record_b);
        }
        M('users')->where( 'id', $user_id)->update($usersUpdate);

//        com_integral_log
        //添加用户积分记录
        $c_i_l = [
            'com_id'=>$Info['com_id'],
            'user_id'=>$user_id,
            'type' => 0,
            'integral_b'=> $record_b,
            'integral_a'=> $record_a,
            'create_time'=>$time,
            'year'=>date('Y',$time),
            'month'=>date('m',$time),
            'year_month'=>strtotime(date('Y-m',$time)),
            'event_id'=>$c_i_p_b_r_e_ID,
        ];
        M('com_integral_log')->insert($c_i_l);
        if($type == 1){//固定积分
            $c_i_l = [
                'com_id'=>$Info['com_id'],
                'user_id'=>$user_id,
                'type' => 1,
                'integral_b'=> $record_b,
                'integral_a'=> $record_a,
                'create_time'=>$time,
                'year'=>date('Y',$time),
                'month'=>date('m',$time),
                'year_month'=>strtotime(date('Y-m',$time)),
                'fixed_id'=>$Info['fixed_id']??0,
            ];
            M('com_integral_log')->insert($c_i_l);
        }elseif ($type == 2){//奖扣任务
            $c_i_l = [
                'com_id'=>$Info['com_id'],
                'user_id'=>$user_id,
                'type' => 2,
                'integral_b'=> $record_b,
                'integral_a'=> $record_a,
                'create_time'=>$time,
                'year'=>date('Y',$time),
                'month'=>date('m',$time),
                'year_month'=>strtotime(date('Y-m',$time)),
                'prize_buckle_type'=>$Info['type'],
            ];
            M('com_integral_log')->insert($c_i_l);
        }elseif ($type == 3){//其他得分
            $c_i_l = [
                'com_id'=>$Info['com_id'],
                'user_id'=>$user_id,
                'type' => 3,
                'integral_b'=> $record_b,
                'integral_a'=> $record_a,
                'create_time'=>$time,
                'year'=>date('Y',$time),
                'month'=>date('m',$time),
                'year_month'=>strtotime(date('Y-m',$time)),
                'leave_type'=>$Info['type'],
            ];
            M('com_integral_log')->insert($c_i_l);
        }


    }
    //冒泡排序
    static public function data_sort($arr,$key)
    {
        $count = count($arr);
        $temp = 0;
        //外层控制排序轮次
        for ($i = 0; $i < $count - 1; $i++) {
            //内层控制每轮比较次数
            for ($j = 0; $j < $count - 1 - $i; $j++) {
                if ($arr[$j][$key] < $arr[$j + 1][$key]) {
                    $temp = $arr[$j];
                    $arr[$j] = $arr[$j + 1];
                    $arr[$j + 1] = $temp;
                }
            }
        }
        return $arr;
    }
    /**
     * @param $start_time  统计时间开始范围 string
     * @param $end_time  统计时间结束范围 string
     * @param $user_id  用户id  int
     * @param $event_ids  事件id集合  array
     * @param int $type 类型,是否加入基础分和工龄分 0不加 1加   int
     */
    //统计用户分值@stone
    static public function statistic_integral($start_time,$end_time,$user_id,$type=0,$event_ids=[]){
        $users = M('users')->where('id',$user_id)->find();
        $status = 0;
        if($start_time < strtotime('2022-01-01')){
            $start_time = strtotime('2022-01-01');
            $status = 1;
        }
        //统计时间范围分值
        $where['a.status'] = 2;
        $where['a.prize_buckle_time'] = ['between',[$start_time,$end_time]];
        $where['c.user_id'] = $user_id;
        $where['c.is_cancellation'] = 0;//未作废
        if(!empty($event_ids)){
            $where['b.event_id'] = ['in',$event_ids];
        }
        $res = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','a.id=b.prize_buckle_id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->where($where)
            ->field('COALESCE(SUM(IF(c.piece_rate=0,c.integral_b,c.piece_rate*c.integral_b)),0) integral_b ')
//                ->field('c.piece_rate,c.integral_b')
            ->find();
        if(!empty($type)){
            $integral_b = $res['integral_b'] + $users['base_integral'] + $users['working_age_integral'];
        }else{
            $integral_b = $res['integral_b'];
        }
        if($status == 1){
            $integral_b = $integral_b + $users['total_integral_b'];
        }
        return $integral_b;
    }
    //统计用户分值@stone
    static public function statistic_integral_a($start_time,$end_time,$user_id,$type=0,$event_ids=[]){
        $users = M('users')->where('id',$user_id)->find();
        //统计时间范围分值
        $where['a.status'] = 2;
        $where['a.prize_buckle_time'] = ['between',[$start_time,$end_time]];
        $where['c.user_id'] = $user_id;
        $where['c.is_cancellation'] = 0;//未作废
        if(!empty($event_ids)){
            $where['b.event_id'] = ['in',$event_ids];
        }
        $res = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','a.id=b.prize_buckle_id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->where($where)
            ->field('COALESCE(SUM(IF(c.piece_rate=0,c.integral_a,c.piece_rate*c.integral_a)),0) integral_b ')
//                ->field('c.piece_rate,c.integral_b')
            ->find();
        if(!empty($type)){
            $integral_b = $res['integral_b'] + $users['base_integral'] + $users['working_age_integral'];
        }else{
            $integral_b = $res['integral_b'];
        }
        return $integral_b;
    }
    //统计奖扣任务数据@stone
    static public function statistic_prize_buckle($start_time,$end_time,$user_id){
        $users = M('users')->where('id',$user_id)->find();
        //统计时间范围分值
        $where['a.status'] = 2;
        $where['a.prize_buckle_time'] = ['between',[$start_time,$end_time]];
        $where['a.first_check_user_id'] = $user_id;
        $where['c.is_cancellation'] = 0;//未作废
        $res = M('com_integral_prize_buckle a')
            ->join('com_integral_prize_buckle_relation_event b','a.id=b.prize_buckle_id','right')
            ->join('com_integral_event_relation_users c','c.event_id=b.id','right')
            ->where($where)
            ->field('COALESCE(SUM(IF(c.integral_b>0,IF(c.piece_rate=0,c.integral_b,c.piece_rate*c.integral_b),0)),0) integral_b_add,
             COALESCE(SUM(IF(c.integral_b<0,IF(c.piece_rate=0,c.integral_b,c.piece_rate*c.integral_b),0)),0) integral_b_del,
             COALESCE(count(c.id),0) people_sum')
            ->find();
        return $res;
    }

}
